import { ForbiddenException, Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { TaskComment, TaskCommentReply, User } from '../../entities';
import { CreateCommentReplyDto } from './dto/create-comment-reply.dto';
import { UpdateCommentReplyDto } from './dto/update-comment-reply.dto';

@Injectable()
export class TaskCommentReplyService {
  constructor(
    @InjectRepository(TaskCommentReply)
    private taskCommentReplyRepository: Repository<TaskCommentReply>,
    @InjectRepository(TaskComment)
    private taskCommentRepository: Repository<TaskComment>,
    @InjectRepository(User)
    private userRepository: Repository<User>,
  ) {}

  /**
   * 创建评论回复
   */
  async createReply(
    createCommentReplyDto: CreateCommentReplyDto,
    userId: string,
  ): Promise<TaskCommentReply> {
    const { content, commentId } = createCommentReplyDto;

    // 检查评论是否存在
    const comment = await this.taskCommentRepository.findOne({
      where: { id: commentId },
    });
    if (!comment) {
      throw new NotFoundException(`评论 ID ${commentId} 不存在`);
    }

    // 创建新回复
    const reply = this.taskCommentReplyRepository.create({
      content,
      commentId,
      userId,
    });

    return this.taskCommentReplyRepository.save(reply);
  }

  /**
   * 获取评论的所有回复
   */
  async getCommentReplies(commentId: string): Promise<TaskCommentReply[]> {
    // 检查评论是否存在
    const comment = await this.taskCommentRepository.findOne({
      where: { id: commentId },
    });
    if (!comment) {
      throw new NotFoundException(`评论 ID ${commentId} 不存在`);
    }

    return this.taskCommentReplyRepository.find({
      where: { commentId },
      relations: ['user'],
      order: { createdAt: 'ASC' }, // 按时间顺序排列
    });
  }

  /**
   * 获取回复详情
   */
  async getReplyById(id: string): Promise<TaskCommentReply> {
    const reply = await this.taskCommentReplyRepository.findOne({
      where: { id },
      relations: ['user'],
    });

    if (!reply) {
      throw new NotFoundException(`回复 ID ${id} 不存在`);
    }

    return reply;
  }

  /**
   * 更新回复
   */
  async updateReply(
    id: string,
    updateCommentReplyDto: UpdateCommentReplyDto,
    userId: string,
  ): Promise<TaskCommentReply> {
    const reply = await this.taskCommentReplyRepository.findOne({
      where: { id },
    });

    if (!reply) {
      throw new NotFoundException(`回复 ID ${id} 不存在`);
    }

    // 只有回复创建者才能更新回复
    if (reply.userId !== userId) {
      throw new ForbiddenException('您没有权限更新此回复');
    }

    // 更新回复内容
    reply.content = updateCommentReplyDto.content;

    return this.taskCommentReplyRepository.save(reply);
  }

  /**
   * 删除回复
   */
  async deleteReply(id: string, userId: string): Promise<void> {
    const reply = await this.taskCommentReplyRepository.findOne({
      where: { id },
    });

    if (!reply) {
      throw new NotFoundException(`回复 ID ${id} 不存在`);
    }

    // 只有回复创建者才能删除回复
    if (reply.userId !== userId) {
      throw new ForbiddenException('您没有权限删除此回复');
    }

    await this.taskCommentReplyRepository.remove(reply);
  }
} 